package com.ztesoft.web.index.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.DateUtils;
import com.ztesoft.framework.util.Utils;
import com.ztesoft.web.baseconfig.db.dao.DmPlanDao;
import com.ztesoft.web.baseconfig.db.dao.DmPlanRelationDao;
import com.ztesoft.web.baseconfig.db.po.DmPlanPO;
import com.ztesoft.web.common.customdb.dao.DmPlanCustomDao;
import com.ztesoft.web.common.customdb.dao.DmTaskStageCustomDao;
import com.ztesoft.web.common.customdb.dao.SysModuleCustomDao;
import com.ztesoft.web.common.customdb.dao.dto.ApprovaTaskStageDto;
import com.ztesoft.web.common.customdb.dao.dto.ApprovalDto;
import com.ztesoft.web.common.customdb.dao.dto.DmTaskStageDto;
import com.ztesoft.web.common.customdb.dao.dto.SysModuleDto;
import com.ztesoft.web.common.db.dao.DmDao;
import com.ztesoft.web.common.service.IOperationLogService;
import com.ztesoft.web.index.db.dao.IndexDao;
import com.ztesoft.web.index.db.po.SpaceDataPO;
import com.ztesoft.web.index.service.IIndexService;
import com.ztesoft.web.taskgenerator.db.dao.DmTaskDao;

/**
 * @Description 
 * @author Chen.Shitian
 * @date 2015年9月6日 下午8:09:02
 * @since 1.0
 *
 */
@Service("indexService")
public class IndexServiceImpl implements IIndexService {

	private static final ZTEsoftLogManager logger = ZTEsoftLogManager.getLogger(IndexServiceImpl.class);
	
	@Autowired
	private DmTaskStageCustomDao dmTaskStageCustomDao;
	@Autowired
	private DmTaskDao dmTaskDao;
	@Autowired
	private IOperationLogService operationLogService;
	
	@Autowired
	private IndexDao indexDao;
	@Autowired 
	private SysModuleCustomDao sysModuleDao;

	@Autowired
	private DmDao dmDao;
	
	@Autowired
	private DmPlanDao planDao;
	
	@Autowired
	private DmPlanCustomDao planCustomDao;
	
	@Override
	public BigDecimal getCheckUpData(int dataType, int nodeId) {
		List<Integer> nodeIds = getNodeIds(nodeId);
		return indexDao.getCheckUpData(dataType, nodeIds);
	}

	@Override
	public BigDecimal getCleanUpData(int dataType, int nodeId) {
		List<Integer> nodeIds = getNodeIds(nodeId);
		return indexDao.getCleanUpData(dataType, nodeIds);
	}

	@Override
	public SpaceDataPO getSpaceSize(int detectionType, int nodeId) {
		List<Integer> nodeIds = getNodeIds(nodeId);
		return indexDao.getSpaceSize(detectionType, nodeIds);
	}

	@Override
	public BigDecimal getBackUpDataSize(int sourceType, int nodeId,
			String createDate,int offset) {
		List<Integer> nodeIds = getNodeIds(nodeId);
		return indexDao.getBackUpDataSize(sourceType,nodeIds,createDate,offset) ;
	}

	@Override
	public BigDecimal getCheckDataSize(int sourceType, int nodeId,
			String createDate,int offset) {
		List<Integer> nodeIds = getNodeIds(nodeId);
		return indexDao.getCheckDataSize(sourceType,nodeIds,createDate,offset) ;
	}

	@Override
	public BigDecimal getResultDataSize(int sourceType, int nodeId,
			String createDate,int offset) {
		List<Integer> nodeIds = getNodeIds(nodeId);
		return indexDao.getResultDataSize(sourceType,nodeIds,createDate,offset) ;
	}

	@Override
	public int getIsCheckNum(int sourceType, int nodeId) {
		List<Integer> nodeIds = getNodeIds(nodeId);
		return indexDao.getIsCheckNum(sourceType,nodeIds);
	}

	@Override
	public int searchTaskNum(Integer sourceType, Integer nodeId, String state,
			Date date) {
		List<Integer> nodeIds = getNodeIds(nodeId);
		return indexDao.searchTaskNum(sourceType,nodeIds,state,date);
	}

	private List<Integer> getNodeIds(Integer nodeId) {
		List<Integer> nodeIds = new ArrayList<Integer>();
		boolean flag=true;
		List<SysModuleDto> list = null;
		List<Integer> tempStr = new ArrayList<Integer>();
		if(nodeId==-1){
			nodeIds=null;
		}else{
			nodeIds.add(nodeId);
			tempStr.add(nodeId);
			while(flag){
				list = new ArrayList<SysModuleDto>();
				list = sysModuleDao.selectSysModuleByParentId(tempStr);
				if(list.size()>0){
					tempStr = new ArrayList<Integer>();
					for (SysModuleDto sysModuleDto : list) {
						nodeIds.add(sysModuleDto.getModuleId());
						tempStr.add( sysModuleDto.getModuleId());
					}
				}else{
					flag = false;
				}
			}
		}
		return nodeIds;
	}

	
	@Override
	public List<ApprovalDto> gryApp(ApprovalDto record) {
		List<ApprovalDto> resultList = dmTaskStageCustomDao.selectForApproval(record.getPlanName(), record.getCheckState());
		Iterator<ApprovalDto> ite = resultList.iterator();
		while (ite.hasNext()) {
			if (Utils.isEmpty(ite.next().getDmTaskStageDtoList())) {
				ite.remove();
			}
		}
		return resultList;
	}

	@Override
	public int[] updateApp(ApprovaTaskStageDto taskStage) {
		int[] result = { 0, 0 };
		int isCheck = (int)taskStage.getIsCheck();
		if (isCheck == -1) {//更新计划为草稿箱
			updatePlanDraft(new int[]{(int)taskStage.getDmTaskId()});
			taskStage.setCheckDesc("|审核拒绝后取消计划|"+taskStage.getCheckDesc());
		}
		int taskStageResult = dmTaskStageCustomDao.updateApp(taskStage);
		if (isCheck == 1 || isCheck == -1) {
			//更新DM为00X
			dmDao.updateByLimit("DM_"+taskStage.getCheckObjName(), "00X", DateUtils.getDBCurrentTime(), taskStage.getDmTaskId(), 
					taskStage.getDmStrategyId(), null, null, null);
		}
		operationLogService.add("审核任务环节|TASK_ID:" + taskStage.getDmTaskId() + "tableName:"
				+ taskStage.getCheckObjName()
				+ (isCheck == 0 ? "|通过" : "|拒绝" + "||审批理由:" + taskStage.getCheckDesc()));
		int waitCheck = dmTaskStageCustomDao.qryCount(taskStage.getDmTaskId(), 2);// 是否都处理完
		result[0] = taskStageResult;
		if (waitCheck == 0) {// 如果处理完，看看是否都处理为失败
			// int conut =
			// dmTaskStageCustomDao.qryCount(taskStage.getDmTaskId(),null);
			waitCheck = dmTaskStageCustomDao.qryCount(taskStage.getDmTaskId(), 0);
			if (waitCheck > 0) {
				result[1] = dmTaskDao.updateTaskById_(0, taskStage.getDmTaskId());
				operationLogService.add("审核任务|TASK_ID:" + taskStage.getDmTaskId() + "|通过" + "||审批理由:"
						+ taskStage.getCheckDesc());
			} else {
//				result[1] = dmTaskDao.updateTaskById_(1, taskStage.getDmTaskId());
				updateTask(new int[]{(int)taskStage.getDmTaskId()}, isCheck, taskStage.getCheckDesc());
//				operationLogService.add("审核任务|TASK_ID:" + taskStage.getDmTaskId() + "|拒绝" + "||审批理由:"
//						+ taskStage.getCheckDesc());
				result[1] = 1;
			}
		}
		return result;
	}

	@Override
	public int updateTask(int[] taskIdArr, int isCheck, String desc) {
		if (isCheck == -1) {//更新计划为草稿箱		
			updatePlanDraft(taskIdArr);
			desc = "|审核拒绝后取消计划|" + desc;
		}
		dmTaskStageCustomDao.updateTaskStage_(isCheck, taskIdArr, desc);
		/*
		 * 
		 */
		int waitCheck;
		List<DmTaskStageDto> list;
		for (int taskId : taskIdArr) {
			
			if (isCheck == 1 || isCheck == -1) {
				list = dmTaskStageCustomDao.selectTaskStageList(taskId, null, 0, "00A");
				for (DmTaskStageDto dto : list) {
					//更新DM为00X
					dmDao.updateByLimit("DM_"+dto.getCheckObjName(), "00X", DateUtils.getDBCurrentTime(), dto.getDmTaskId(), 
							dto.getDmStrategyId(), null, null, null);
				}
			}
			
			waitCheck = dmTaskStageCustomDao.qryCount(taskId, 2);// 是否都处理完
			if (waitCheck == 0) {
				dmTaskDao.updateTask_(isCheck, new int[] { taskId });
				operationLogService.add("审核任务|TASK_ID:" + taskId + (isCheck == 0 ? "|通过" : "|拒绝") + "||审批理由:" + desc);
			}
		}
		return 1;
	}
	
	/**
	 * 更新草稿
SELECT * from dm_plan where DM_PLAN_ID = 12249;
SELECT * from dm_plan_relation where DM_PLAN_ID = 12249;
SELECT * from dm_strategy where DM_STRATEGY_ID = 15181;
SELECT * from dm_strategy_dataobj_rel where DM_PLAN_ID = 12249;
	   * TODO
	 * @param taskIdArr
	 */
	private void updatePlanDraft(int[] taskIdArr) {
//		for (int taskId : taskIdArr) {				
//			DmPlanPO planPO = planCustomDao.selectByTaskId(taskId);
//			DmPlanRelationDao dmPlanRelationDao;
//			if (planPO!=null) {				
//				planPO.setState("00D"); //草稿
//				planDao.updateByPrimaryKey(planPO);
//			}
//		}
	}
	
}
